package com.ugoodtech.mdcc.client.service.impl;

/* Copyright (C) Ugoodtech, Inc - All Rights Reserved
 * Unauthorized copying of this file, via any medium is strictly prohibited
 * Proprietary and confidential
 */

import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.client.service.RequestLogService;
import com.ugoodtech.mdcc.core.domain.QRequestLog;
import com.ugoodtech.mdcc.core.domain.RequestLog;
import com.ugoodtech.mdcc.core.repository.RequestLogRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ReuqestLogServiceImpl implements RequestLogService {
    @Autowired
    private RequestLogRepository newsRepository;

    @Override
    public RequestLog getLastRequest(){
       return queryRequestLog(null,null,null,new PageRequest(0,1)).getContent().get(0);
    }


    @Override
    public Page<RequestLog> queryRequestLog(String key, Date startDate, Date endDate, Pageable pageable) {
        QRequestLog qRequestLog = QRequestLog.requestLog;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qRequestLog.deleted.isFalse());
        if (!StringUtils.isEmpty(key)) {
            BooleanBuilder orBuilder = new BooleanBuilder();
            orBuilder.or(qRequestLog.url.like("%" + key + "%"));
            builder.and(orBuilder);
        }

        if (null != startDate) {
            builder.and(qRequestLog.creationTime.after(startDate));
        }

        if (null != endDate) {
            builder.and(qRequestLog.creationTime.before(endDate));
        }
        Sort sort = new Sort(Sort.Direction.DESC,  "creationTime");
        pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);
        return newsRepository.findAll(builder, pageable);
    }
}
